package com.ddxz.middleground.meta.collect;

import com.ddxz.middleground.meta.util.DdxzMetaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;

import static com.ddxz.middleground.meta.util.ErrorStatus.DRIVE_NOT_FOUND;
import static com.ddxz.middleground.meta.util.ErrorStatus.SOURCE_NOT_VALID;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/8/23
 */

public class MySqlCollect extends BaseDataSourceCollect {
    protected MySqlCollect(String host, Integer port, String instance, String user, String password) {
        super(host, port, instance, user, password);
    }

    @Override
    protected void getConnection() {
        try {
            Connection conn = DriverManager.getConnection(String.format(URL, host, port, instance), user, password);
            conn.createStatement().execute(SQL);
            conn.close();
        } catch (Exception e) {
            throw new DdxzMetaException(SOURCE_NOT_VALID, e);
        }
    }

    private static final String SQL = "SELECT 1";

    private static final Logger logger = LoggerFactory.getLogger(MySqlCollect.class);

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    private static final String URL ="jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=UTF-8&useSSL=false&&serverTimezone=UTC";

    static {
        try {
            Class.forName(DRIVER);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new DdxzMetaException(DRIVE_NOT_FOUND, e);
        }
    }
}
